#include "appwindow.h"
#include "ui_appwindow.h"
#include <QTimer>
#include <QCloseEvent>
#include "common.h"
#include "Settings.h"
#include "usercredentialsdialog.h"

AppWindow::AppWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::AppWindow)
{
    ui->setupUi(this);
    client = NULL;
    if(!getLoginAndPassword())
    {
        close();
        g_application->quit();
        return;
    }
    client = new OnetClient(this, iLogin, iPassword);
    connect(client, SIGNAL(logMessage(QString)), SLOT(onMessage(QString)));
    connect(client, SIGNAL(registerUser(QString,QString,QString,QString)),
            SLOT(onNickAdded(QString,QString,QString,QString)));
    connect(ui->sendButton, SIGNAL(clicked()), SLOT(onSend()));
    connect(ui->sendLine, SIGNAL(returnPressed()), SLOT(onSend()));
    connect(ui->userList, SIGNAL(itemDoubleClicked(QListWidgetItem*)), SLOT(onItemClick(QListWidgetItem*)));
    connect(client, SIGNAL(connected()), SLOT(storeSavedCredentials()));
    onMessage("Connecting to host...");
    client->connectToHost();
}

bool AppWindow::getLoginAndPassword()
{
    iLogin = QCMSettings::Current()->Get("OnetLogin");
    iPassword = QCMSettings::Current()->Get("OnetPassword");
    if(iLogin.isEmpty())
    {
        UserCredentialsDialog dialog(this);
        dialog.setModal(true);
        dialog.show();
        QEventLoop loop;
        connect(&dialog, SIGNAL(dataProvided(QString,QString)),
                SLOT(credentialsProvided(QString,QString)));
        connect(&dialog, SIGNAL(cancelled()), SLOT(credentialsCancelled()));
        connect(this, SIGNAL(cancelWait()), &loop, SLOT(quit()));
        loop.exec();
    }
    return !iLogin.isEmpty();
}

void AppWindow::credentialsProvided(QString aNick, QString aPassowrd)
{
    iLogin = aNick;
    iPassword = aPassowrd;
    if(iLogin.startsWith('~'))
        iPassword.clear();
    if(iPassword.isEmpty() && !iLogin.startsWith('~'))
        iLogin = "~" + iLogin;
    emit cancelWait();
}

void AppWindow::credentialsCancelled()
{
    emit cancelWait();
}

void AppWindow::closeEvent(QCloseEvent *e)
{
    QMainWindow::closeEvent(e);
    if(client && client->isConnected())
        client->disconnectHost();
}

AppWindow::~AppWindow()
{
    delete client;
    delete ui;
}

void AppWindow::onMessage(QString aMsg)
{
    ui->debugTextOutput->appendPlainText(aMsg);
}

void AppWindow::onSend()
{
    QString text = ui->sendLine->text();
    if(text.startsWith('/'))
        client->sendRaw(text.right(text.length()-1));
    else
    {
        client->sendRaw(QString("PRIVMSG %1 :%2").arg(iLastRoom).arg(text));
    }
    ui->sendLine->setText("");
}

void AppWindow::onNickAdded(QString aChannel, QString aNick, QString aPrefix, QString aSuffix)
{
    iLastRoom = aChannel;
    QList<QListWidgetItem*> items = ui->userList->findItems(aNick, 0);
    if(items.empty())
    {
        ui->userList->addItem(aNick);
        ui->userList->sortItems();
    }
}

void AppWindow::onItemClick(QListWidgetItem *item)
{
    if(ui->sendLine->text().isEmpty())
    {
        ui->sendLine->setText(QString("PRIVMSG %1 :").arg(item->text()));
    }
}

void AppWindow::storeSavedCredentials()
{
    QCMSettings::Current()->Set("OnetLogin", iLogin);
    QCMSettings::Current()->Set("OnetPassword", iPassword);
}
